package usersDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MySqlUsersDao implements UsersDAO {

	@Override
	public int add(UsersEntity u) {
		String sql = "insert into news_users (unmae,upwd) values (?,?)";
		return DBUtils.executeUpdate(sql, u.getUname(), u.getUpwd());
	}

	@Override
	public int del(long id) {
		String sql = "delete from news_users where uid=?";
		return DBUtils.executeUpdate(sql, id);
	}

	@Override
	public int update(UsersEntity u) {
		String sql = "update news_users set uname=?,upwd=? where uid=?";
		return DBUtils.executeUpdate(sql, u.getUname(), u.getUpwd(), u.getId());
	}

	@Override
	public UsersEntity find(Long id) {
		Connection conn = null;
		PreparedStatement prs = null;
		ResultSet rs = null;
		UsersEntity user = null;
		String sql = "select * from news_users where uid=?";
		try {
			conn = DBUtils.getConnection();
			prs = conn.prepareStatement(sql);
			prs.setLong(1, id);
			rs = prs.executeQuery();
			if (rs.next()) {
				user = new UsersEntity();
				user.setId(rs.getLong("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs, prs, conn);
		}
		return user;
	}

	@Override
	public List<UsersEntity> query() {
		List<UsersEntity> list = new ArrayList<UsersEntity>();
		Connection conn = null;
		PreparedStatement prs = null;
		ResultSet rs = null;
		UsersEntity user = null;
		String sql = "select * from news_users";
		try {
			conn = DBUtils.getConnection();
			prs = conn.prepareStatement(sql);
			rs = prs.executeQuery();
			while (rs.next()) {
				user = new UsersEntity();
				user.setId(rs.getLong("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
				list.add(user);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs, prs, conn);
		}
		return list;
	}

	@Override
	public UsersEntity login(String name, String pass) {
		UsersEntity user = null;
		Connection conn = null;
		PreparedStatement prs = null;
		ResultSet rs = null;
		String sql = "select * from news_users where uname=? and upwd=?";
		try {
			conn = DBUtils.getConnection();
			prs = conn.prepareStatement(sql);
			prs.setString(1, name);
			prs.setString(2, pass);
			rs = prs.executeQuery();
			if (rs.next()) {
				user = new UsersEntity();
				user.setId(rs.getLong("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(rs, prs, conn);
		}
		return user;
	}

}
